

//判断是否有特殊字符
export const specialStr = (str) => {
    str = str.replace(/\s/ig, '')
    return !/^[a-zA-Z0-9\u4E00-\u9FA5]+$/ig.test(str)
}
//时间戳转时间格式
export const getLocalTime = (number = 0) => {
    return dateFormat(new Date(number))
}
//时间字符串格式统一
export const dateStrFormat = (str) => {
    if (str == undefined)
        str = ''
    return (str + '').replace(/\-/g, '.').replace(/\//g, '.')
}

//时间保持2位，加零处理
export const allUnit = (num) => {
    if (num < 10)
        num = '0' + num
    return num;
}

//时间格式处理
export const dateFormat = (time, newSplit = '.', all = true) => {
    let nowTime = new Date();
    let year = time.getFullYear(),
        month = time.getMonth() + 1, //月
        date = time.getDate(), //日
        hours = time.getHours(), //时
        minute = time.getMinutes(), //分
        seconds = time.getSeconds(); //秒
    //当前时间
    let day = year + newSplit + allUnit(month) + newSplit + allUnit(date);
    if (newSplit == '.') {
        if (nowTime.toLocaleString().split(' ')[0].replace(/\//g, '-') == time.toLocaleString().split(' ')[0].replace(/\//g, '-')) {
            day = '今天'
        } else {
            nowTime = new Date(nowTime.setDate(nowTime.getDate() - 1))
            if (nowTime.toLocaleString().split(' ')[0].replace(/\//g, '-') == time.toLocaleString().split(' ')[0].replace(/\//g, '-')) {
                day = '昨天'
            } else if (nowTime.getFullYear() == time.getFullYear()) {
                day = allUnit(month) + newSplit + allUnit(date);
            }
        }
    }
    if (all)
        day += ' ' + allUnit(hours) + ':' + allUnit(minute);

    return day;
}

//获取时间 传入数字 -1 前一天
export const GetDateStr = (AddDayCount, dd = new Date()) => {
    dd.setDate(dd.getDate() + AddDayCount);
    return dateFormat(dd, '-', false)
};

//Ajax
export class HttpService {
    static query(config = {}) {
        if (config.async == undefined)
            config.async = true
        var request = new XMLHttpRequest();
        var sign = config.url.indexOf('?') > -1
            ? '&'
            : '?';
        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                var status = request.status;
                if (status >= 200 && status < 300) {
                    let res = request.responseText;
                    try {
                        res = JSON.parse(res);
                    } catch (e) {
                        if (res.indexOf('?xml') > -1) {
                            res = JSON.parse(xmlToJson(res));
                        }
                    } finally {
                        config.success(res);
                    }
                } else {
                    if (config.fail) {
                        return config.fail(status);
                    } else {
                        Tips('连接服务异常');
                    }
                }
            }
        };
        setTimeout(() => {
            if (request.status != 200) {
                request.abort();
                //request.complete();
                console.log('ajax timeout');
            }
        }, 1000 * 6);
        if (config.type == 'post') {
            request.open('POST', config.url, config.async);
            request.send(config.data);
        } else {
            request.open('GET', config.url + sign + HttpService.formatParams(config.data), config.async);
            request.send(null);
        }
    }
    static formatParams(data) {
        var arr = [];
        for (var name in data) {
            arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
        }
        arr.push(("ver=" + Math.random()).replace(".", ""));
        return arr.join("&");
    }
}

//消息提示
export let msgTout = null
export const Tips = (msg = '服务异常', duration = 3) => {
    var msgObj = document.querySelector('.tips'),
        msgSpan = msgObj ?
            msgObj.querySelector('span') :
            null;
    if (msgObj == undefined) {
        msgObj = document.createElement('div');
        msgSpan = document.createElement('span');
        msgObj.appendChild(msgSpan);
        msgObj.className = 'tips';
        document.body.appendChild(msgObj);
    }
    msgSpan.innerHTML = msg;
    msgObj.style.display = 'block';
    clearTimeout(msgTout);
    if (duration == 0)
        return;
    msgTout = setTimeout(function() {
        msgObj.style.display = 'none';
    }, duration * 1000);
}

//图片上传
export const imgUpload = (data, callback) => {
    var inputObj = document.getElementById(data.inputId);
    var imgObj = document.getElementById(data.imgId);
    if (inputObj.files && inputObj.files[0]) {
        var fr = new FileReader();
        fr.onload = function() {
            image.src = fr.result;
        };
        var file = inputObj.files[0];
        fr.readAsDataURL(inputObj.files[0]);
        var image = new Image();
        image.onload = function() {
            if (typeof data.scale != 'undefined' && data.scale != '') {
                var scaleW = data.scale.split(':')[0];
                var scaleH = data.scale.split(':')[1];
                if (image.width / scaleW != image.height / scaleH) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片比例上传（' + data.scale + '）！');
                    return;
                }
            } else {
                var tips = '';
                var valid = true;
                if (typeof data.width != 'undefined' && data.width != '' && image.width != data.width) {
                    tips = '宽度：' + data.width + 'px，';
                    valid = false;
                }
                if (typeof data.height != 'undefined' && data.height != '' && image.height != data.height) {
                    tips += '高度：' + data.height + 'px，';
                    valid = false;
                }
                if (!valid) {
                    inputObj.value = imgObj.src = '';
                    callback(false, '请按图片尺寸上传(' + tips.substr(0, tips.length - 1) + ')');
                    return;
                }
            }
            if (typeof data.size != 'undefined' && data.size != '' && inputObj.files[0].size / 1024 / 1024 > data.size) {
                var sizeLimit = data.size + 'M';
                if (data.size < 1) {
                    sizeLimit = (data.size * 1024).toFixed(0) + 'KB';
                }
                inputObj.value = imgObj.src = '';
                callback(false, '请上传小于 ' + sizeLimit + ' 的图片');
                return;
            }
            var filename = file.name;
            var imgSize = image.src.length;
            var imgUrl = window.URL.createObjectURL(inputObj.files[0]);
            imgObj.src = imgUrl;

            //图片压缩
            imgCompress(imgUrl, imgSize, data.presWidth, data.presQuality, function(baseStr) {
                //base64转二进制流图片
                var text = window.atob(baseStr.split(",")[1]);
                var buffer = new Uint8Array(baseStr.length);
                var pecent = 0,
                    loop = null;
                for (var i = 0; i < text.length; i++) {
                    buffer[i] = text.charCodeAt(i);
                }
                var imgType = baseStr.split(';')[0].split(':')[1];
                var blob = getBlob([buffer], imgType);
                blob.filename = filename;
                callback(true, blob);
                //下载图片查看
                // var link = document.createElement('a');
                // link.href = window.URL.createObjectURL(blob);
                // link.download = filename;
                // link.click();
                // window.URL.revokeObjectURL(link.href);
            });
        };
    } else {
        //IE下，使用滤镜处理，给定宽高
        inputObj.select();
        var imgSrc = document.selection.createRange().text;
        var localImagId = document.getElementById(data.imgIeId);
        //设置初始大小
        var ieWidth = ieHeight = 100;
        if (typeof data.width != 'undefined' && !isNaN(data.width))
            ieWidth = data.width;
        if (typeof data.height != 'undefined' && !isNaN(data.height))
            ieHeight = data.height;
        localImagId.style.width = ieWidth + "px";
        localImagId.style.height = ieHeight + "px";
        //图片异常的捕捉，防止用户修改后缀来伪造图片
        try {
            localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
            localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
        } catch (e) {
            callback('请选择正确的图片格式!');
            return false;
        }
        imgObj.style.display = 'none';
        document.selection.empty();
    }
}

//获取blob对象的兼容性写法
export const getBlob = (buffer, format, filename) => {
    try {
        return new Blob(buffer, {
            type: format,
            filename
        });
    } catch (e) {
        var bb = new(window.BlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder);
        buffer.forEach(function(buf) {
            bb.append(buf);
        });
        return bb.getBlob(format);
    }
}

//图片压缩
export const imgCompress = (imgUrl, initSize, setWidth = 600, quality = 0.8, callBack) => {
    var setHeight,
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d'),
        img = new Image();
    img.src = imgUrl;
    img.onload = function() {
        if (setWidth > img.width)
            setWidth = img.width
        setHeight = setWidth / img.width * img.height;
        canvas.width = setWidth;
        canvas.height = setHeight;
        context.drawImage(img, 0, 0, setWidth, setHeight);
        var basestr = canvas.toDataURL('image/jpeg', quality); //后面的小数表示图片的质量
        var newSize = basestr.length;
        console.log('oldSize：' + initSize);
        console.log('newSize：' + newSize);
        console.log('percent：' + (newSize * 100 / initSize).toFixed(2) + '%');
        callBack(basestr);
    }
};

//xmlToJson
export const xmlToJson = (xmlStr) => {
    var xotree = new XML.ObjTree();
    var dumper = new JKL.Dumper();
    var tree = xotree.parseXML(xmlStr);
    var jsonStr = dumper.dump(tree);
    return jsonStr;
};

//URL获取关键字内容
export const urlKey = (keyName, newStr = location.href) => {
    var reg = new RegExp(keyName + '=([^&]*)(&|$)', 'i');
    var keyValue = reg.test(newStr)
        ? reg.exec(newStr)[1]
        : '';
    return keyValue.replace(/\s/ig, '');
};

//Ajax图片上传(地址、方法)
export const AjaxUploadImgUrl = 'http://192.168.2.11:1235/php/filedownload_image.php?FileId='
export const AjaxUploadImg = (file, callBack) => {
    let data = new FormData();
    data.append('Filedata', file, file.filename);
    HttpService.query({
        url: '/php/fileuploadUUID.php?AppId=0&AppCode=0&UserName=public',
        type: 'post',
        data: data,
        success: (res => {
            const status = res.split(':')[0],
                msg = res.split(':')[1];
            callBack({status, msg})
        })
    })
};

//图片全屏查看
export const viewerImg = (src = 'src', e) => {
    let ele = '',
        url = '';
    if (typeof e == 'string') {
        ele = src;
        url = e;
    } else {
        ele = e;
        url = src;
    }
    let viewer = new Viewer(ele.target, {
        url: url,
        button: false,
        toolbar: false,
        title: false,
        navbar: false,
        transition: true,
        viewed: function() {
            document.querySelector('.viewer-in').onclick = function() {
                viewer.hide();
            };
            document.querySelector('.viewer-canvas').onclick = function() {
                viewer.hide();
            };
        }
    });
};

//判断访问终端
export const browser = () => {
    let u = navigator.userAgent;
    return {
        trident: u.indexOf('Trident') > -1, //IE内核x
        presto: u.indexOf('Presto') > -1, //opera内核
        webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
        gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
        mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
        ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
        android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
        iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
        iPad: u.indexOf('iPad') > -1, //是否iPad
        webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
        weixin: u.indexOf('MicroMessenger') > -1, //是否微信
        qq: u.match(/\sQQ/i) == " qq" //是否QQ
    };
};

/**
 * 获取地理
 * @param lng
 * @param lat
 * @returns {Function}
 */
export const getAddree = (lng, lat) => {
    let lnglatXY = [lng, lat],address = ''; //已知点坐标
    let geocoder = new AMap.Geocoder({radius: 1000, extensions: "all"});
    geocoder.getAddress(lnglatXY, function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
            return result.regeocode.formattedAddress; //返回地址描述
        }
    });
};
/**
 * 处理访问不到图片
 */
export const imgonError = (defaultImg,e) => {
    e.target.setAttribute('src',defaultImg);
};
/**
 * 页面数据
 * @type {{Devices: Array}}
 */
export let pageData = {
    Devices:[]
};
